import org.codehaus.groovy.grails.plugins.authorize.user.AuthUserStatus;
import org.springframework.validation.BindException;

class AuthUser {

    def static hasMany = [roles: AuthRole]
    def static fetchMode = [roles: "eager"]

    String username
    String passwordEnc
    String firstname
    String lastname
    String email
    String hash
    String status = AuthUserStatus.PENDING;
    Date created = new Date()
    Date lastAccess = new Date()

    Set roles = new HashSet()

    static constraints = {
        username(nullable: false, blank: false, unique: true)
        passwordEnc(nullable: false, blank: false)
        email(nullable: false, email: true, unique: true)
        firstname(nullable: true)
        lastname(nullable: true)
        created(nullable: false)
        status(nullable: false)
        lastAccess(nullable: true)
    }

    def boolean hasRole(String roleName) {
        for (AuthRole role in roles) {
            if (role.name.equals(roleName)) {
                return true;
            }
        }
        return false;
    }

    def boolean hasRole(AuthRole role) {
        return roles.contains(role)
    }

    def String generateHash() {
        this.hash = "${username}:${email}:${new Date()}".encodeAsPassword()
        return this.hash
    }

    def void generateErrors() {
        if (!errors) {
            errors = new BindException()
        }
    }

    String toString() {"${username}"}

    boolean equals(Object obj) {
        AuthUser other = obj as AuthUser
        if (!other) {
            return false
        }

        if (username.equals(other.username)) {
            return true;
        }
    }
}	
